<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use App\Models\Local\GrabGarbage AS LocalGrabGarbage;       //本地数据模型
use App\Models\Headquarters\GrabGarbage AS HQGrabGarbage;       //总部数据模型
use Illuminate\Support\Facades\DB;
use Illuminate\Database\QueryException;
use Log;

/**
 * 上报本地抓斗数据到总部
 */
class GrabGarbageReportJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    protected $local_conn; //本地连接
    protected $remote_conn; //总部连接
    protected $local_data_table; //本地保存的原始数据集合
    protected $remote_data_table; //总部保存的数据集合

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($params=null)
    {
        $this->local_conn = $params && isset($params['local_conn']) ? $params['local_conn'] : '';
        $this->remote_conn = $params && isset($params['remote_conn']) ? $params['remote_conn'] : '';
        $this->local_data_table = $params && isset($params['local_data_table']) ? $params['local_data_table'] : '';
        $this->remote_data_table = $params && isset($params['remote_data_table']) ? $params['remote_data_table'] : '';
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $localGrabGarbageObj = (new LocalGrabGarbage())->setConnection($this->local_conn)->setTable($this->local_data_table);
        $hQGrabGarbageObj = (new HQGrabGarbage())->setConnection($this->remote_conn)->setTable($this->remote_data_table);
        $notReportDataList = $localGrabGarbageObj->findNotReport();
        try {
            foreach($notReportDataList as $row){
                $param = array(
                    'id' => $row->id,
                    'allsn' => $row->allsn,
                    'sn'=> $row->sn,
                    'time'=> $row->time,
                    'che'=> $row->che,
                    'dou'=> $row->dou,
                    'liao'=> $row->liao,
                    'code'=> $row->code,
                    'lost'=> $row->lost,
                    'hev'=> $row->hev,
                    'created_at' => $row->created_at,
                    'updated_at' => $row->updated_at
                );
                
                $res = $hQGrabGarbageObj->insertOne($param);
                if($res){
                    $row->flag = 1;
                    $row->save();
                }
            }
        } catch (QueryException $e) {
            Log::info('=========上报总部抓斗数据失败=========');
            DB::rollback();
        }
    }
}
